package com.lagou.concurrent.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        //初始最大线程数是3，当超过3个任务时，会扩容至5
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                3, 5,
                1, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getId() + "[" + finalI + "] -- 开始");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getId() + "[" + finalI + "] -- 结束");
                }
            });
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //优雅地关闭线程池
        executor.shutdown();
        boolean flag = true;
        try {
            do {
                //使用awaitTermination方法来等待运行的线程执行完毕再关闭线程池
                flag = !executor.awaitTermination(1, TimeUnit.SECONDS);
                System.out.println(flag);
            } while (flag);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程池关闭成功。。。");
        System.out.println(Thread.currentThread().getId());
    }
}
